package com.yanqu.road.server.handle;

import com.yanqu.road.NettyMgr;
import com.yanqu.road.server.ChannelBaseServer;
import com.yanqu.road.server.connect.ChannelCross3LinkedControl;
import com.yanqu.road.connect.ServerConnectionGroup;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.task.ChannelCommandTask;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@Sharable
public class ChannelServerHandler extends SimpleChannelInboundHandler<YanQuMessage> {

    private static Logger logger = LogManager.getLogger(ChannelServerHandler.class.getName());
    private String handlerName;

    public ChannelServerHandler() {
        handlerName = "channelServer handler";
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("receive a connect : " + ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("connection disconnected : " + ctx.channel().remoteAddress());
        ServerConnectionGroup client = ctx.channel().attr(NettyMgr.LINKED_CLIENT).get();
        if (client != null) {
            ChannelCross3LinkedControl.closeConnection(ctx);
            logger.error("close the connection to agent disconnected. connection :  {}",ctx.channel().remoteAddress());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("connect error : " + ctx.channel().remoteAddress() + ", error : " + cause);

        ServerConnectionGroup client = ctx.channel().attr(NettyMgr.LINKED_CLIENT).get();
        if (client != null) {
            ChannelCross3LinkedControl.closeConnection(ctx);
            logger.error(toMessage("caught exception the connection to agent disconnected. connection : "
                    + ctx.channel().remoteAddress()));
        }

        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, YanQuMessage msg) throws Exception {
        ChannelCommandTask cmdWrapper = new ChannelCommandTask(ctx, msg);
        ChannelBaseServer.getServerCommandExecutor().execute(cmdWrapper);
    }

    private String toMessage(String msg) {
        return "[" + handlerName + "] " + msg;
    }
}
